Imports System.Drawing
Imports System.IO

Friend Class TileCache
    Private ReadOnly _fullPath As String

    Public Sub New(serviceName__1 As String)
        ServiceName = serviceName__1

        _fullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "TileCache", serviceName__1)
        Directory.CreateDirectory(_fullPath)
    End Sub

    Public Property ServiceName() As String
        Get
            Return m_ServiceName
        End Get
        Set(value As String)
            m_ServiceName = Value
        End Set
    End Property
    Private m_ServiceName As String

    ''' <summary>
    '''
    ''' </summary>
    ''' <param name="zoom"></param>
    ''' <param name="x"></param>
    ''' <param name="y"></param>
    ''' <returns></returns>
    Public Function [Get](zoom As Integer, x As Integer, y As Integer) As Bitmap
        Try
            Dim pathToTile = Path.Combine(_fullPath, zoom.ToString(), x.ToString())

            Dim monthPrior = DateTime.Today.Subtract(New TimeSpan(30, 0, 0, 0))
            Dim fi = New FileInfo(pathToTile)
            If fi.CreationTime.CompareTo(monthPrior) < 0 Then
                'If the tile file is over 1 month old
                Return Nothing
            End If
            'then we want to return null so a new tile is downloaded.
            Dim filepath As String = Path.Combine(pathToTile, y.ToString())
            If Not File.Exists(filepath) Then
                Return Nothing
            End If

            Dim tile = New Bitmap(filepath)

            Return tile
        Catch
            Return Nothing
        End Try
    End Function

    ''' <summary>
    '''
    ''' </summary>
    ''' <param name="tile"></param>
    ''' <returns></returns>
    Public Function Put(tile As Tile) As Boolean
        Try
            Dim pathToTile As String = Path.Combine(_fullPath, tile.ZoomLevel.ToString())
            pathToTile = Path.Combine(pathToTile, tile.X.ToString())

            Directory.CreateDirectory(pathToTile)

            tile.Bitmap.Save(Path.Combine(pathToTile, tile.Y.ToString()))

            Return True
        Catch
            Return False
        End Try
    End Function
End Class
